#include <EventLoopThread.h>

EventLoopThread::EventLoopThread(const std::string name, ThreadInitCallback cb)
    : name_(name),
      cb_(cb),
      existing_(true),
      loop_(nullptr)
{
}

EventLoop *EventLoopThread::startLoop()
{
    existing_ = false;
    assert(!thread_);
    thread_ = std::make_unique<std::thread>(
        [&]()
        {
            EventLoop loop;
            if (cb_)
            {
                cb_(&loop);
            }
            {
                std::lock_guard<std::mutex> lock(mutex_);
                loop_ = &loop;
                cond_.notify_one();
            }
            loop.loop();
        });
    std::unique_lock<std::mutex> lock(mutex_);
    cond_.wait(lock, [&](){ return loop_ != nullptr; });
    return loop_;
}

EventLoopThread::~EventLoopThread()
{
    existing_ = true;
    if (loop_)
    {
        loop_->quit(); // FIX:如果startLoop后马上析构，可能导致先析构执行quit，后执行loop_->loop()，从而无法join
    }
    if (thread_ && thread_->joinable())
    {
        thread_->join();
    }
}
